package com.hulk.dryad.web.oauth2.base.component;

import com.hulk.dryad.manage.security.component.DryadAuthExceptionEntryPoint;

import com.hulk.dryad.manage.security.component.PermitAllSecurityUrlProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;

/**
 * @author hulk
 * @date 2019/6/22
 * <p>
 * 1. tokenServices 2. 支持 获取用户全部信息
 */
@Slf4j
public class DryadResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {

	@Autowired
	protected DryadAuthExceptionEntryPoint authExceptionEntryPoint;

	@Autowired
	private DefaultTokenServices defaultTokenServices;

	@Autowired
	private PermitAllSecurityUrlProperties permitAllSecurityUrlProperties;

	@Autowired
	private DryadBearerTokenExtractor tokenExtractor;


	/**
	 * 默认的配置，对外暴露
	 * @param httpSecurity
	 */
	@Override
	@SneakyThrows
	public void configure(HttpSecurity httpSecurity) {
		// 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
		httpSecurity.headers().frameOptions().disable();
		ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity
				.authorizeRequests();
		permitAllSecurityUrlProperties.getIgnoreUrls().forEach(url -> registry.antMatchers(url).permitAll());
		registry.anyRequest().authenticated().and().csrf().disable();
	}

	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {
				/*
                DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
				UserAuthenticationConverter userTokenConverter = new DryadUserAuthenticationConverter();
				accessTokenConverter.setUserTokenConverter(userTokenConverter);
		        defaultTokenServices.setTokenStore();
				 */
		resources.authenticationEntryPoint(authExceptionEntryPoint).tokenExtractor(tokenExtractor)
				.tokenServices(defaultTokenServices);
	}



}
